package cn.ygh.bbo.system.web.controller;

import cn.ygh.bbo.common.annotation.Log;
import cn.ygh.bbo.common.annotation.OperationType;
import cn.ygh.bbo.framerwork.core.ClientInfo;
import cn.ygh.bbo.framerwork.core.Grid;
import cn.ygh.bbo.framerwork.core.ResultAjax;
import cn.ygh.bbo.common.exception.TipException;
import cn.ygh.bbo.system.bean.Role;
import cn.ygh.bbo.system.service.RoleService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 描述：角色  RestPageController
 * @author ygh
 */
@Controller
@RequestMapping("/restpage/role")
public class RoleController {

    private final Logger logger= LoggerFactory.getLogger(getClass());

    @Autowired
    RoleService roleService;

    /**
     * 查询列表api 带总数
     * @param request 请求
     * @param response 响应
     * @param clientInfo, 查询条件
     * @return
     */
    @RequiresPermissions("system:role:query")
    @ResponseBody
    @RequestMapping(value = "/query",method = RequestMethod.GET)
    public Grid grid(HttpServletRequest request, HttpServletResponse response, ClientInfo clientInfo, Role search){
        search.setOrderValue(clientInfo.realSort().trim());
        if (clientInfo.getPageNo()==0){
            throw new TipException("pageNum can not zero");
        }
        Grid grid=roleService.listGrid(search,PageRequest.of(clientInfo.getPageNo(),clientInfo.getPageSize()));
        return grid;
    }

    /**
     * 查询列表api 不带总数
     * @param request 请求
     * @param response 响应
     * @return
     */
    @RequiresPermissions("Role:query")
    @ResponseBody
    @RequestMapping(value = "/queryList",method = RequestMethod.GET)
    public Map<String,Object> queryList(HttpServletRequest request, HttpServletResponse response
            , Role search, Integer adminId){
        Map<String,Object>result=new HashMap<>();
        List<Role>roleList=roleService.listfind(search
                ,null);
        result.put("roleList", roleList);
        List<Integer>roleIds=new ArrayList<>();
        if (adminId!=null) {
            //放入角色列表
            List<Role> roles = roleService.listfindByAdminId(adminId);
            roleIds=roles.stream().map(e->e.getId()).collect(Collectors.toList());
        }
        result.put("roleIds",roleIds);
        return result;
    }

    /**
     * 创建数据api
     * @param request 请求
     * @param response 响应
     * @param obj 创建对象
     * @param errors 验证异常
     * @return
     */
    @Log(value="Role",operationId=OperationType.CREATE)
    @RequiresPermissions("system:role:create")
    @ResponseBody
    @RequestMapping(value = "/create",method = RequestMethod.POST)
    public ResultAjax create(HttpServletRequest request, HttpServletResponse response, @Valid Role obj, BindingResult errors){
        if (errors.hasErrors()){
            FieldError err0=(FieldError)errors.getAllErrors().get(0);
            return ResultAjax.fail("添加失败！"+err0.getField()+":"+err0.getDefaultMessage());
        }
        roleService.save(obj);
        return ResultAjax.success(obj);
    }

    /**
     * 权限分配
     * @param request 请求
     * @param response 响应
     * @return
     */
    @Log(value="Role",operationId=OperationType.CREATE)
    @RequiresPermissions("system:role:permission")
    @ResponseBody
    @RequestMapping(value = "/createPermission",method = RequestMethod.POST)
    public ResultAjax createPermission(HttpServletRequest request, HttpServletResponse response
            ,Integer roleId,String permissionIds){
        roleService.createPermission(roleId,permissionIds);
        return ResultAjax.success();
    }

    /**
     * 更新数据api
     * @param request 请求
     * @param response 响应
     * @param obj 更新对象
     * @param errors 验证异常
     * @return
     */
    @Log(value="Role",operationId=OperationType.UPDATE)
    @RequiresPermissions("system:role:update")
    @ResponseBody
    @RequestMapping(value = "/update",method = RequestMethod.POST)
    public ResultAjax update(HttpServletRequest request, HttpServletResponse response, @Valid Role obj, BindingResult errors){
        if (errors.hasErrors()){
            FieldError err0=(FieldError)errors.getAllErrors().get(0);
            return ResultAjax.fail("更新失败！"+err0.getField()+":"+err0.getDefaultMessage());
        }
        roleService.update(obj);
        return ResultAjax.success(obj);
    }

    /**
     * 根据Ids删除
     * @param request 请求
     * @param response 响应
     * @param ids
     * @return
     */
    @Log(value="Role",operationId=OperationType.DEL)
    @RequiresPermissions("system:role:del")
    @ResponseBody
    @RequestMapping(value = "/del",method = RequestMethod.POST)
    public ResultAjax del(HttpServletRequest request, HttpServletResponse response, String ids){
        if (StringUtils.isBlank(ids)){
            return ResultAjax.fail("ids不能为空");
        }
        String[] idList=ids.split(",");
        roleService.deleteByIds(idList);
        return ResultAjax.success();
    }

}
